package com.googlecode.jmicroerp.wicket.reports;

import com.googlecode.jmicroerp.wicket.DefaultViewPage;

import com.googlecode.jmicroerp.model.Magazin;
import com.googlecode.jmicroerp.service.BonService;
import com.googlecode.jmicroerp.service.GenericService;
import com.googlecode.jmicroerp.wicket.SecuredWebSession;
import com.googlecode.jmicroerp.wicket.reports.ReportsPage;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.Model;

import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.extensions.markup.html.form.DateTextField;
import org.apache.wicket.extensions.yui.calendar.DatePicker;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.text.DateFormat;

// import java.util.Date;


public class ReportsPage extends DefaultViewPage {
    
    @SpringBean(name = "bonService")
    private BonService bonService;
    
    @SpringBean(name = "genericService")
    private GenericService<Magazin> magazinService;
    private Magazin magazin;
    
    private String numeMag = ((SecuredWebSession) getSession()).getMagazin().getDenumire(); 
    
    private Date today = new Date(); // data curenta
    private Date dateS = addDays(today, 0); // data azi resetata la miezul noptii
    private Date dateF = addDays(today, 1); // data maine cu data curenta + o zi

    //numar de zile diferenta intre zilele selectate
    private Long difDates = ((dateF.getTime() - dateS.getTime()) / (1000 * 60 * 60 * 24)); 
    
    public static Date addDays(Date date, int days) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.add(Calendar.DATE, days);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        //cal.set(Calendar.AM_PM, Calendar.AM);
        cal.set(Calendar.MILLISECOND, 0);
                 
        return cal.getTime();
    }

    private BigDecimal difD = BigDecimal.ONE;
    private Locale locale = new Locale("ro");    
    
    // detect if user can select magazin on reports
    // private boolean SelectEnabled = true;
    // private String roluri = ((SecuredWebSession) getSession()).getUserDetail().getRoluri();
    private String NumeUser = ((SecuredWebSession) getSession()).getUserDetail().getUsername();
    
    private class BonView extends ListView<Object[]> {

        public BonView(String id, List<Object[]> data) {
            super(id, data);
        }

        @Override
        protected void populateItem(ListItem<Object[]> li) {
            Object[] object = li.getModelObject();
            li.add(new Label("magazin", object[0].toString()));
            li.add(new Label("produs", object[1].toString()));
            // li.add(new Label("cantitate", String.format( "%.2f", object[2])));
            li.add(new Label("cantitate", object[2].toString()));
            li.add(new Label("pret", object[3].toString()));
            
            BigDecimal valSub = new BigDecimal(object[4].toString()); 
            li.add(new Label("subtotal", valSub.setScale(2,BigDecimal.ROUND_HALF_EVEN).toString()));

            BigDecimal valM = new BigDecimal(object[2].toString());
            li.add(new Label("medie", valM.divide(difD,2,RoundingMode.HALF_UP).toString()));
        }
    }
    
    private Long selected = ((SecuredWebSession) getSession()).getMagazin().getId();
    
    public ReportsPage() {
        
        final Label lbMagazin = new Label("lbMagazin", numeMag);
        add(lbMagazin);
        add(new FeedbackPanel("feedback"));
 
        magazin = ((SecuredWebSession) getSession()).getMagazin();
        final DropDownChoice<Magazin> ddcMagazin = new DropDownChoice<Magazin>(
                "sites", 
                new PropertyModel<Magazin>(this, "magazin"),
                new LoadableDetachableModel<List<Magazin>>() {
                    @Override
                    protected List<Magazin> load() {
                        return magazinService.getList(Magazin.class, null, null);
                    }
                }, 
                new ChoiceRenderer<Magazin>("denumire", "id")
        );
        if ( !NumeUser.equals("admin") ) {
            ddcMagazin.add(new AttributeAppender("disabled", true, new Model<String>("disabled"), " "));
        }
        
        final DateTextField dtDataStart = new DateTextField("dataStart", new PropertyModel<Date>(this, "dateS"), "dd.MM.yyyy");
        dtDataStart.add(new DatePicker());
        // dtDataStart.setRequired(true);
        
        final DateTextField dtDataStop = new DateTextField("dataStop", new PropertyModel<Date>(this, "dateF"), "dd.MM.yyyy");
        dtDataStop.add(new DatePicker());
        // dtDataStop.setRequired(true);

        final Label lbPerioada = new Label("lbPerioada", "Astazi");
        add(lbPerioada);
        
        final BonView bonAziView = new BonView("bonuriAzi", bonService.queryBonuriProduseByMagazin(dateS, dateF, selected));
        final Label lblVandAzi = new Label("vanzariAzi", bonService.queryVanzariByMagazin(dateS, dateF, selected).toString());
        
        /* Object[] bonDataAzi = bonService.queryBonuriToday();
        final Label lblSumAzi = new Label("totalSumaAzi", bonDataAzi[1] == null ? "---" : bonDataAzi[1].toString()); */
        
        add(bonAziView);
        add(lblVandAzi);
        
        Form<?> form = new Form<Void>("form") {
			@Override
			protected void onSubmit() {
				
                if ( NumeUser.equals("admin") ) {
                    lbMagazin.setDefaultModelObject(magazin.getDenumire());
                    lbMagazin.modelChanged();
                    // ddcMagazin.add(new AttributeAppender("disabled", true, new Model<String>("disabled"), " "));
                    selected = magazin.getId();
                } else {
                    selected = ((SecuredWebSession) getSession()).getMagazin().getId();
                }

				// info("Magazin selectat : " + magazin.getDenumire() + ", ID : " + selected + ", Data Start: " + DateFormat.getDateInstance(DateFormat.SHORT).format(dateS) + ", Data Stop: " + DateFormat.getDateInstance(DateFormat.SHORT).format(dateF));
                
                //numar de zile diferenta intre zilele selectate
                difDates = ((dateF.getTime() - dateS.getTime()) / (1000 * 60 * 60 * 24));                
                lbPerioada.setDefaultModelObject(DateFormat.getDateInstance(DateFormat.SHORT, locale).format(dateS) + " - " + DateFormat.getDateInstance(DateFormat.SHORT, locale).format(dateF) + " ( " + difDates  + " zile)" );
                lbPerioada.modelChanged();
                
                bonAziView.setDefaultModelObject(bonService.queryBonuriProduseByMagazin(dateS, dateF, selected));
                bonAziView.modelChanged();
                
                difD = new BigDecimal(difDates.toString());
                lblVandAzi.setDefaultModelObject(bonService.queryVanzariByMagazin(dateS, dateF, selected).toString());
                lblVandAzi.modelChanged();
 
			}
		};

		form.add(ddcMagazin);
        form.add(dtDataStart);
        form.add(dtDataStop);
		add(form);
        
    }
}